package pri.hillchen.springbootstd.bms.common.base;


import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import pri.hillchen.springbootstd.bms.entity.system.AccessLog;
import pri.hillchen.springbootstd.bms.service.system.AccessLogService;

import java.util.List;
import java.util.concurrent.*;

/**
 * Created by hillchen on 2017/10/22.
 */
@Component
public class AccessLogHandler implements InitializingBean {
    @Autowired
    private AccessLogService accessLogService;

    @Override
    public void afterPropertiesSet() throws Exception {
        starScheduledThread();
    }

    /*@Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent)  throws BeansException {
        starScheduledThread();
    }*/

    private void starScheduledThread(){
        new ScheduledThreadPoolExecutor(1).scheduleAtFixedRate(
                new ThreadFactory(){
                    @Override
                    public Thread newThread(Runnable r) {
                        return new Thread(r,"accesslog insert");
                    }
                }.newThread(new Runnable() {
                    @Override
                    public void run() {
                        List<AccessLog> accessLogs = LogHelper.logdequeue();
                        if(!CollectionUtils.isEmpty(accessLogs)){
                            try{
                                accessLogService.insertBatch(accessLogs);
                            }catch (Exception e){
                                e.printStackTrace();
                            }

                        }
                    }
                })
                ,0,10, TimeUnit.MILLISECONDS
        );
    }
}
